package io.renren.socket.client.test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Date;
import java.util.Set;

import io.renren.htby.utils.IOTSUtils;

/**
 * 控制系统的 socket异步连接
 * 
 * @author lfy.xys
 * @date 2018年5月22日
 *
 */
public class CtrlConnClientRunnable_2018_06_11 implements Runnable {

	private String ip;
	private int port;
	private String sendMsg;// 发送的消息
	private String receiveText;// 接收的消息
	private ByteBuffer rBuffer = ByteBuffer.allocate(1024);
	private int count = 0;
	
	
	public CtrlConnClientRunnable_2018_06_11(String ip, int port, String sendMsg) {
		this.ip = ip;
		this.port = port;
		this.sendMsg = sendMsg;
	}

	@Override
	public void run() {
		try {
			InetSocketAddress SERVER = new InetSocketAddress(ip, port);
			SocketChannel socketChannel = SocketChannel.open();
			socketChannel.configureBlocking(false);
			Selector selector = Selector.open();
			socketChannel.register(selector, SelectionKey.OP_CONNECT);
			socketChannel.connect(SERVER);
			SocketChannel client = null;

			while (true) {
				selector.select();
				Set<SelectionKey> keySet = selector.selectedKeys();
				for (final SelectionKey selectionKey : keySet) {
					if (selectionKey.isConnectable()) {
						client = (SocketChannel) selectionKey.channel();
						if (client.isConnectionPending()) {
							client.finishConnect();
							System.out.println("connect success !");
							System.out.println(sendMsg);
							client.write(ByteBuffer.wrap(sendMsg.getBytes()));
						}
						client.register(selector, SelectionKey.OP_READ);
						System.out.println("isConnectable");
					} else if (selectionKey.isReadable()) {
						boolean failure = true;
						client = (SocketChannel) selectionKey.channel();
						rBuffer.clear();
						try {
							count = client.read(rBuffer);
							failure = false;
						} catch (Exception e) {
							System.out.println("断开连接");
//							e.printStackTrace();
						}
						
						if (count <= 0 || failure) {
							selectionKey.cancel(); // Some JDK implementations run into an infinite loop without this.
							System.out.println("服务端关闭");
						} else {
							receiveText = new String(rBuffer.array(), 0, count);
							client = (SocketChannel) selectionKey.channel();
							client.register(selector, SelectionKey.OP_READ);
							
							System.out.println(receiveText);
						}
						System.out.println("isReadable");
					}  
				}
				keySet.clear();
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	

	public static void main(String[] args) {
		CtrlConnClientRunnable_2018_06_11 r = new CtrlConnClientRunnable_2018_06_11("localhost", 8888, "bbb在政治");
		r.run();
	}

}
